package fun.util.daohelper;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

/**
 * Author: bin
 * Date: Jan 9, 2006
 * Time: 10:34:34 PM
 */
public class AbstractEntity <K extends AbstractPrimaryKey> implements Serializable {

    K pk = null;

    public K getPk() {
        return pk;
    }

    protected void setPk( K pk ) {
        this.pk = pk;
    }

    /**
     *
     * @param oid - object id
     */
    protected void setOid(Serializable oid) {
        ParameterizedType parentType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<K> pkClass = (Class<K>) parentType.getActualTypeArguments()[0];

        pk = PrimaryKeyUtil.createPK(pkClass, oid);
    }

    public Serializable getOid() {
        return pk == null ? null : pk.getValue();
    }

    public int hashCode() {
        if ( pk == null ) {
            return super.hashCode();
        }
        else {
            return pk.hashCode();
        }
    }

    /**
     * @deprecated see getOid()
     * @return object id
     */
    public Serializable getUid() {
        return getOid();
    }

    protected void setUid( Serializable oid ) {
        setOid( oid );
    }

    public boolean isUnsaved() {
        return pk == null;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (getPk() == null || obj == null) {
            return false;
        }

        if (!this.getClass().isInstance(obj)) {
            return false;
        }

        AbstractEntity model = (AbstractEntity) obj;
        return this.getPk().equals(model.getPk());
    }

}
